<?php

use think\Db;

if (!function_exists('matchLatLng')) {
    function matchLatLng($latlng) {
        $match = "/^\d{1,3}\.\d{1,30}$/";
        return preg_match($match, $latlng) ? $latlng : 0;
    }
}


if (!function_exists('getDistanceBuilder')) {
    function getDistanceBuilder($lat, $lng) {
        return "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((". matchLatLng($lat) . " * PI() / 180 - latitude * PI() / 180) / 2), 2) + COS(". matchLatLng($lat). " * PI() / 180) * COS(latitude * PI() / 180) * POW(SIN((". matchLatLng($lng). " * PI() / 180 - longitude * PI() / 180) / 2), 2))) * 1000) AS distance";
    }
}
if (!function_exists('getDistanceBuildertwo')) {
    function getDistanceBuildertwo($lat, $lng) {
        return "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((". matchLatLng($lat) . " * PI() / 180 - latitude * PI() / 180) / 2), 2) + COS(". matchLatLng($lat). " * PI() / 180) * COS(latitude * PI() / 180) * POW(SIN((". matchLatLng($lng). " * PI() / 180 - longitude * PI() / 180) / 2), 2))) * 1000) AS distance";
    }
}
/**
 * 微信公众号模板消发送
 * @param array $param
 * @return bool|string
 */
if (!function_exists('send_public_template_message')) {
    function send_public_template_message($param = []){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . get_public_access_token();
        $curl = curl_init();

        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);

        curl_setopt($curl,CURLOPT_POST,true);
        curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($param));

        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
        $result = curl_exec($curl);
        curl_close($curl);
        file_put_contents("access_token.json",json_encode($result).PHP_EOL, FILE_APPEND|LOCK_EX);
        return $result;
    }
}

/**
 * 库存预警通知
 * @param array $param
 * @return bool|string
 */
if (!function_exists('inventory_warning_notice')) {
    function inventory_warning_notice($good_id){
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];

        $good_info = Db::name('shopro_goods')->where('id',$good_id)->field('id,title,shopro_store_id')->find();
        $user_list = Db::name('shopro_user_store')->where('store_id',$good_info['shopro_store_id'])->select();
        $store_info = Db::name('shopro_store')->where('id',$good_info['shopro_store_id'])->find();
        $stock_count = Db::name('shopro_goods_sku_price')->where('goods_id',$good_id)->sum('stock');

        foreach ($user_list as $v){

            $unionid = Db::name('shopro_user_oauth')->where('user_id',$v['user_id'])->value('unionid');
            $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');

            if ($gzh_openid){

                \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                    'touser' => $gzh_openid,
                    'template_id' => '_GoC3I5mpi4m4wAh-YhH_gv9joO_tM9SUEQ7ng3uTmI',
                    'miniprogram'=>[
                        'appid'=>$app_id,
//                        'path'=>'pages/goods/detail?id='.$good_id,
                    ],
                    'data' => [
                        'first'    => array('value' => '您好，您有一款商品库存低于警戒值:', 'color' => '#ff0000'),
                        'keyword1' => array('title' => '服务商名称', 'value' => $store_info['name'], 'color' => '#000000'),
                        'keyword2' => array('title' => '系列名称', 'value' => $good_info['title'], 'color' => '#000000'),
                        'keyword3' => array('title' => '库存数量', 'value' => $stock_count, 'color' => '#000000'),
                    ]
                ], 'shopro');
            }

        }



    }
}

/**
 * 帮卖团长接收的模板
 * @param array $param
 * @return bool|string
 */
if (!function_exists('help_the_sales_leader_to_receive_the_template')) {
    function help_the_sales_leader_to_receive_the_template($groupon_id){
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];

        $groupon_info = Db::name('shopro_activity_groupon')
            ->alias('g')
            ->join('user u','u.id = g.user_id')
            ->join('shopro_goods s','s.id = g.goods_id')
            ->where('g.id',$groupon_id)
            ->field('g.id,g.user_id,g.goods_id,g.activity_id,g.createtime,u.nickname,s.title,s.subtitle')
            ->find();

        $user_list = Db::name('user')->where('parent_user_id',$groupon_info['user_id'])->select();

        foreach ($user_list as $v){
            
            $unionid = Db::name('shopro_user_oauth')->where('user_id',$v['id'])->value('unionid');
            $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');

            if ($gzh_openid){

                \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                    'touser' => $gzh_openid,
                    'template_id' => 'ZRem3v-UjqWoS4T-nt4C93JcsCbB2jpASw1By22MNVc',
                    'miniprogram'=>[
                        'appid'=>$app_id,
                        'pagepath'=>'pages/activity/groupon/detail?id='.$groupon_id,
                    ],
                    'data' => [
                        'first'    => array('value' => '您关注的团长：'.$groupon_info['nickname'].'发布了新的团购', 'color' => '#ff0000'),
                        'keyword1' => array('title' => '服务名称', 'value' => $groupon_info['title'], 'color' => '#000000'),
                        'keyword2' => array('title' => '生效时间', 'value' => date('Y-m-d H:i:s', $groupon_info['createtime']), 'color' => '#000000'),
                        'keyword3' => array('title' => '服务内容', 'value' => $groupon_info['subtitle'].'正在团购中', 'color' => '#000000'),
//                        'remark' => array('title' => '服务类型', 'value' => '水机安装', 'color' => '#000000'),
                    ]
                ], 'shopro');
            }
            
        }



    }
}
/**
 * 普通团员收到的模板
 * @param array $param
 * @return bool|string
 */
if (!function_exists('template_received_by_regular_members')) {
    function template_received_by_regular_members($groupon_id){
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];

        $groupon_info = Db::name('shopro_activity_groupon')
            ->alias('g')
            ->join('user u','u.id = g.user_id')
            ->join('shopro_goods s','s.id = g.goods_id')
            ->where('g.id',$groupon_id)
            ->field('g.id,g.user_id,g.goods_id,g.activity_id,g.createtime,u.nickname,s.title,s.subtitle')
            ->find();

        $user_list = Db::name('user')->where('parent_user_id',$groupon_info['user_id'])->select();

        foreach ($user_list as $v){

            $unionid = Db::name('shopro_user_oauth')->where('user_id',$v['id'])->value('unionid');
            $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');

            if ($gzh_openid){

                \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                    'touser' => $gzh_openid,
                    'template_id' => 'ZRem3v-UjqWoS4T-nt4C93JcsCbB2jpASw1By22MNVc',
                    'miniprogram'=>[
                        'appid'=>$app_id,
                        'pagepath'=>'pages/activity/groupon/detail?id='.$groupon_id,
                    ],
                    'data' => [
                        'first'    => array('value' => '您关注的团长：'.$groupon_info['nickname'].'发布了新的团购', 'color' => '#ff0000'),
                        'keyword1' => array('title' => '服务名称', 'value' => $groupon_info['title'], 'color' => '#000000'),
                        'keyword2' => array('title' => '生效时间', 'value' => date('Y-m-d H:i:s', $groupon_info['createtime']), 'color' => '#000000'),
                        'keyword3' => array('title' => '服务内容', 'value' => $groupon_info['subtitle'].'正在团购中', 'color' => '#000000'),
//                        'remark' => array('title' => '服务类型', 'value' => '水机安装', 'color' => '#000000'),
                    ]
                ], 'shopro');
            }

        }



    }
}
//已对接
/**
 * 新订单通知团长接收的【团员参与团给团长发】
 * @param array $param
 * @return bool|string
 */
if (!function_exists('notify_the_head_of_the_new_order_to_receive')) {
    function notify_the_head_of_the_new_order_to_receive($groupon_id){
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];




        $groupon_info = Db::name('shopro_activity_groupon')
            ->alias('g')
            ->join('user u','u.id = g.user_id')
            ->join('shopro_goods s','s.id = g.goods_id')
            ->where('g.id',$groupon_id)
            ->field('g.id,g.user_id,g.goods_id,g.activity_id,g.createtime,u.nickname,s.title,s.subtitle')
            ->find();


            $unionid = Db::name('shopro_user_oauth')->where('user_id',$groupon_info['user_id'])->value('unionid');
            $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');

            if ($gzh_openid){
                $count = Db::name('shopro_activity_groupon_log')->where('groupon_id',$groupon_id)->count();

                \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                    'touser' => $gzh_openid,
                    'template_id' => 'g1V9BDbTUu-vie46jXy5VV7FILaNNeBp-hq--ZiKoGo',
                    'miniprogram'=>[
                        'appid'=>$app_id,
                        'pagepath'=>'pages/activity/groupon/detail?id='.$groupon_id,
                    ],
                    'data' => [
                        'first'    => array('value' => '您有新的订单，请前往订单管理页查看', 'color' => '#ff0000'),
                        'keyword1' => array('title' => '订单编号', 'value' => '跟团号'.$groupon_id, 'color' => '#000000'),
                        'keyword2' => array('title' => '时间', 'value' => date('Y-m-d H:i:s', time()), 'color' => '#000000'),
//                        'keyword3' => array('title' => '服务内容', 'value' => $groupon_info['subtitle'].'正在团购中', 'color' => '#000000'),
                        'remark' => array('title' => '备注', 'value' => '您有'.$count.'个新订单，请及时查看', 'color' => '#000000'),
                    ]
                ], 'shopro');
            }



    }
}

//已对接（微信订单退款完成）
/**
 * 退款完成通知【团员】
 * @param array $param
 * @return bool|string
 */
if (!function_exists('refund_completion_notice')) {
    function refund_completion_notice($groupon_id,$user_id,$money){
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];




        $groupon_info = Db::name('shopro_activity_groupon')
            ->alias('g')
            ->join('user u','u.id = g.user_id')
            ->join('shopro_goods s','s.id = g.goods_id')
            ->where('g.id',$groupon_id)
            ->field('g.id,g.user_id,g.goods_id,g.activity_id,g.createtime,u.nickname,s.title,s.subtitle')
            ->find();

        $unionid = Db::name('shopro_user_oauth')->where('user_id',$user_id)->value('unionid');
        $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');

        if ($gzh_openid){


            \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                'touser' => $gzh_openid,
                'template_id' => '_B00myiofrVNfgcGlPeC67He0u_ORHt45PL8KfKsNis',
                'miniprogram'=>[
                    'appid'=>$app_id,
                    'pagepath'=>'pages/activity/groupon/detail?id='.$groupon_id,
                ],
                'data' => [
                    'first'    => array('value' => '您的跟团订单有新的退款！', 'color' => '#ff0000'),
                    'keyword1' => array('title' => '订单编号', 'value' => '跟团号'.$groupon_id, 'color' => '#000000'),
                    'keyword2' => array('title' => '商品名称', 'value' => $groupon_info['title'], 'color' => '#000000'),
                    'keyword3' => array('title' => '退款金额', 'value' => $money, 'color' => '#000000'),
                    'remark' => array('title' => '备注', 'value' => '团购名称'.$groupon_info['title'], 'color' => '#000000'),
                ]
            ], 'shopro');
        }







    }
}

//已对接(申请退团时发送)
/**
 * 订单取消通知【团长】
 * @param array $param
 * @return bool|string
 */
if (!function_exists('order_cancellation_notice')) {
    function order_cancellation_notice($user_id,$groupon_id){//申请退款人ID,团ID
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];




        $groupon_info = Db::name('shopro_activity_groupon')
            ->alias('g')
            ->join('user u','u.id = g.user_id')
            ->join('shopro_goods s','s.id = g.goods_id')
            ->where('g.id',$groupon_id)
            ->field('g.id,g.user_id,g.goods_id,g.activity_id,g.createtime,u.nickname,s.title,s.subtitle')
            ->find();


        $unionid = Db::name('shopro_user_oauth')->where('user_id',$groupon_info['user_id'])->value('unionid');
        $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');

        if ($gzh_openid){
            $count = Db::name('shopro_activity_groupon_log')->where('groupon_id',$groupon_id)->count();

            \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                'touser' => $gzh_openid,
                'template_id' => 'TscRpeij0zGTSwxG3cPl4Ax-l3VYEh6ful_sSKG52_g',
                'miniprogram'=>[
                    'appid'=>$app_id,
                    'pagepath'=>'pages/activity/groupon/detail?id='.$groupon_id,
                ],
                'data' => [
                    'first'    => array('value' => $groupon_info['nickname'].',有新的退团申请', 'color' => '#ff0000'),
                    'keyword1' => array('title' => '服务项目', 'value' => $groupon_info['title'], 'color' => '#000000'),
                    'keyword2' => array('title' => '申请时间', 'value' => date('Y-m-d H:i:s', time()), 'color' => '#000000'),
                    'keyword3' => array('title' => '订单号', 'value' => '跟团号'.$groupon_id, 'color' => '#000000'),
                    'keyword4' => array('title' => '申请人', 'value' => Db::name('user')->where('id',$user_id)->value('nickname'), 'color' => '#000000'),
                    'remark' => array('title' => '备注', 'value' => '点击进入小程序团长中心进行操作', 'color' => '#000000'),
                ]
            ], 'shopro');
        }



    }
}
//已对接(申请退团时发送)
/**
 * 订单取消通知【团长】
 * @param array $param
 * @return bool|string
 */
if (!function_exists('order_cancellation_noticetwo')) {
    function order_cancellation_noticetwo($user_id,$groupon_id){//申请退款人ID,团ID
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];




        $groupon_info = Db::name('shopro_activity_groupon')
            ->alias('g')
            ->join('user u','u.id = g.user_id')
            ->join('shopro_goods s','s.id = g.goods_id')
            ->where('g.id',$groupon_id)
            ->field('g.id,g.user_id,g.goods_id,g.activity_id,g.createtime,u.nickname,s.title,s.subtitle')
            ->find();


        $unionid = Db::name('shopro_user_oauth')->where('user_id',$groupon_info['user_id'])->value('unionid');
        $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');

        if ($gzh_openid){
            $count = Db::name('shopro_activity_groupon_log')->where('groupon_id',$groupon_id)->count();

            \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                'touser' => $gzh_openid,
                'template_id' => 'TscRpeij0zGTSwxG3cPl4Ax-l3VYEh6ful_sSKG52_g',
                'miniprogram'=>[
                    'appid'=>$app_id,
                    'pagepath'=>'pages/activity/groupon/detail?id='.$groupon_id,
                ],
                'data' => [
                    'first'    => array('value' => $groupon_info['nickname'].',有新的退团申请', 'color' => '#ff0000'),
                    'keyword1' => array('title' => '服务项目', 'value' => $groupon_info['title'], 'color' => '#000000'),
                    'keyword2' => array('title' => '申请时间', 'value' => date('Y-m-d H:i:s', time()), 'color' => '#000000'),
                    'keyword3' => array('title' => '订单号', 'value' => '跟团号'.$groupon_id, 'color' => '#000000'),
                    'keyword4' => array('title' => '申请人', 'value' => Db::name('user')->where('id',$user_id)->value('nickname'), 'color' => '#000000'),
                    'remark' => array('title' => '备注', 'value' => '点击进入小程序团长中心进行操作', 'color' => '#000000'),
                ]
            ], 'shopro');
        }



    }
}
//已对接（申请退团，团长拒绝后发送）
/**
 * 退款失败提醒【团员】
 * @param array $param
 * @return bool|string
 */
if (!function_exists('refund_failure_reminder')) {
    function refund_failure_reminder($user_id,$money,$ext,$groupon_id){//申请退款人ID,退款金额，拒绝原因，团ID
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];
        $groupon_info = Db::name('shopro_activity_groupon')
            ->alias('g')
            ->join('user u','u.id = g.user_id')
            ->join('shopro_goods s','s.id = g.goods_id')
            ->where('g.id',$groupon_id)
            ->field('g.id,g.user_id,g.goods_id,g.activity_id,g.createtime,u.nickname,s.title,s.subtitle')
            ->find();
        $unionid = Db::name('shopro_user_oauth')->where('user_id',$user_id)->value('unionid');
        $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');
        if ($gzh_openid){
            $count = Db::name('shopro_activity_groupon_log')->where('groupon_id',$groupon_id)->count();
            \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                'touser' => $gzh_openid,
                'template_id' => '4oX1d2t0Nu4VfLC-4y54y7wgdIrfSB1R4H3U7LMwW1g',
                'miniprogram'=>[
                    'appid'=>$app_id,
                    'pagepath'=>'pages/activity/groupon/detail?id='.$groupon_id,
                ],
                'data' => [
                    'first'    => array('value' => '您好，您的退款申请已被团长【'.$groupon_info['nickname'].'】拒绝', 'color' => '#ff0000'),
                    'keyword1' => array('title' => '订单编号', 'value' => '跟团号'.$groupon_id, 'color' => '#000000'),
                    'keyword2' => array('title' => '订单商品', 'value' => $groupon_info['title'], 'color' => '#000000'),
                    'keyword3' => array('title' => '退款金额', 'value' => $money, 'color' => '#000000'),
                    'keyword4' => array('title' => '拒绝原因', 'value' => $ext, 'color' => '#000000'),
                    'remark' => array('title' => '备注', 'value' => '团购名称：'.$groupon_info['nickname'], 'color' => '#000000'),
                ]
            ], 'shopro');
        }
    }
}
//已对接（微信订单支付成功后发送）
/**
 * 用户参加拼团，支付成功后
 * @param array $param
 * @return bool|string
 */
if (!function_exists('after_successful_payment')) {
    function after_successful_payment($user_id,$groupon_id){//参团人ID，团ID
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];
        $groupon_info = Db::name('shopro_activity_groupon')
            ->alias('g')
            ->join('user u','u.id = g.user_id')
            ->join('shopro_goods s','s.id = g.goods_id')
            ->where('g.id',$groupon_id)
            ->field('g.id,g.num,g.user_id,g.goods_id,g.activity_id,g.createtime,u.nickname,s.title,s.subtitle')
            ->find();
        $unionid = Db::name('shopro_user_oauth')->where('user_id',$user_id)->value('unionid');
        $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');
        if ($gzh_openid){
            $count = Db::name('shopro_activity_groupon_log')->where('groupon_id',$groupon_id)->count();
            \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                'touser' => $gzh_openid,
                'template_id' => 'LIA2y60CAhROF_VziXR-pVQPBVhTs9Y8fY1a44pl-jE',
                'miniprogram'=>[
                    'appid'=>$app_id,
                    'pagepath'=>'pages/activity/groupon/detail?id='.$groupon_id,
                ],
                'data' => [
                    'first'    => array('value' => '恭喜您参团成功，快邀请更多好友一起来拼吧！', 'color' => '#ff0000'),
                    'keyword1' => array('title' => '商品名称', 'value' => $groupon_info['title'], 'color' => '#000000'),
                    'keyword2' => array('title' => '拼团人数', 'value' => $groupon_info['num'], 'color' => '#000000'),
                    'keyword3' => array('title' => '拼团时间', 'value' =>date('Y-m-d H:i:s', time()), 'color' => '#000000'),
                ]
            ], 'shopro');
        }
    }
}
//已对接（拼团成功后发送）
/**
 * 成团成功，给用户推送拼团成功消息通知
 * @param array $param
 * @return bool|string
 */
if (!function_exists('clouds_success')) {
    function clouds_success($groupon_id){//团ID
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];
        $groupon_info = Db::name('shopro_activity_groupon')
            ->alias('g')
            ->join('user u','u.id = g.user_id')
            ->join('shopro_goods s','s.id = g.goods_id')
            ->where('g.id',$groupon_id)
            ->field('g.id,g.user_id,g.goods_id,g.activity_id,g.createtime,u.nickname,s.title,s.subtitle')
            ->find();

        $user_list = Db::name('shopro_activity_groupon_log')->where('groupon_id',$groupon_id)->select();
        foreach ($user_list as $v){
            $unionid = Db::name('shopro_user_oauth')->where('user_id',$v['user_id'])->value('unionid');
            $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');
            if ($gzh_openid){
                $count = Db::name('shopro_activity_groupon_log')->where('groupon_id',$groupon_id)->count();
                \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                    'touser' => $gzh_openid,
                    'template_id' => 'Hu-mzaRfVrYdc62YAARv71I66vaJNBiwqwViZzBX-l8',
                    'miniprogram'=>[
                        'appid'=>$app_id,
                        'pagepath'=>'pages/activity/groupon/detail?id='.$groupon_id,
                    ],
                    'data' => [
                        'first'    => array('value' => '恭喜您拼团成功！', 'color' => '#ff0000'),
                        'keyword1' => array('title' => '订单编号', 'value' =>'跟团号'.$groupon_id, 'color' => '#000000'),
                        'keyword2' => array('title' => '团购商品', 'value' => $groupon_info['title'], 'color' => '#000000'),
                    ]
                ], 'shopro');
            }
        }


    }
}
//已对接（微信订单核销成功后发送）
/**
 * 核销通知
 * @param array $param
 * @return bool|string
 */
if (!function_exists('cancel_after_verification_notice')) {
    function cancel_after_verification_notice($order_item_id){//订单规格ID
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];

        $order_item = Db::name('shopro_order_item')->where('id',$order_item_id)->find();

        $unionid = Db::name('shopro_user_oauth')->where('user_id',$order_item['user_id'])->value('unionid');
        $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');
        if ($gzh_openid){

            \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                'touser' => $gzh_openid,
                'template_id' => '81NQwtmgUjOKRv-ZEhp_enrABg7pM9JJqYGxlUX6QlE',
                'miniprogram'=>[
                    'appid'=>$app_id,
                    'pagepath'=>'pages/order/list',
                ],
                'data' => [
                    'first'    => array('value' => '亲爱的小主，您的券已使用。', 'color' => '#ff0000'),
                    'keyword1' => array('title' => '商品名称', 'value' => $order_item['goods_title'], 'color' => '#000000'),
                    'keyword2' => array('title' => '商品金额', 'value' => $order_item['pay_price'], 'color' => '#000000'),
                    'keyword3' => array('title' => '商品数量', 'value' => $order_item['goods_num'], 'color' => '#000000'),
                    'keyword4' => array('title' => '核销时间', 'value' =>date('Y-m-d H:i:s', time()), 'color' => '#000000'),
                ]
            ], 'shopro');
        }


    }
}
/**
 * 用户有人下单，通知商家
 * @param array $param
 * @return bool|string
 */
if (!function_exists('xiadan_shangjia_notice')) {
    function xiadan_shangjia_notice($order_item_id){//订单规格ID
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];

        $order_item = Db::name('shopro_order_item')->where('id',$order_item_id)->find();
        $good_shopro_store_id = $order_item['good_shopro_store_id'];
        $stroe_user_id = Db::name('shopro_user_store')->where('store_id',$good_shopro_store_id)->find();

        $user = Db::name('user')->where('id',$order_item['user_id'])->find();
        $createtime = date('Y-m-d H:i:s', $order_item['createtime']);
        $order = Db::name('shopro_order')->where('id',$order_item['order_id'])->find();


        $unionid = Db::name('shopro_user_oauth')->where('user_id',$stroe_user_id['user_id'])->value('unionid');
        $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');
        if ($gzh_openid){

            \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                'touser' => $gzh_openid,
                'template_id' => 'mcZ0Wpt1H4jVtusaBzkRXCAAqPRx_TVLC0aT81xIoLQ',
                'miniprogram'=>[
                    'appid'=>$app_id,
                    'pagepath'=>'pages/app/merchant/index?storeId='.$good_shopro_store_id,
                ],
                'data' => [
                    'first'    => array('value' => '有人下单啦！', 'color' => '#ff0000'),
                    'keyword1' => array('title' => '下单账号', 'value' => $user['nickname'], 'color' => '#000000'),
                    'keyword2' => array('title' => '下单时间', 'value' => $createtime, 'color' => '#000000'),
                    'keyword3' => array('title' => '下单产品', 'value' => $order_item['goods_title'], 'color' => '#000000'),
                    'keyword4' => array('title' => '下单金额', 'value' =>$order_item['pay_price'], 'color' => '#000000'),
                    'keyword5' => array('title' => '联系电话', 'value' =>$order['phone'], 'color' => '#000000'),
//                    'remark' => array('title' => '备注', 'value' => '团购名称：'.$groupon_info['nickname'], 'color' => '#000000'),
                ]
            ], 'shopro');
        }


    }
}
/**
 * 用户申请退款，通知商家
 * @param array $param
 * @return bool|string
 */
if (!function_exists('tuikuan_shangjia_notice')) {
    function tuikuan_shangjia_notice($aftersale_id){//订单规格ID
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];
        file_put_contents("tuikuan_shangjia_notice.txt",'09'.json_encode(1).PHP_EOL, FILE_APPEND|LOCK_EX);


        $aftersale = Db::name('shopro_order_aftersale')->where('id',$aftersale_id)->find();
        $aftersale_log = Db::name('shopro_order_aftersale_log')->where('order_aftersale_id',$aftersale_id)->find();


        $content = substr($aftersale_log['content'],15);
        $order_item = Db::name('shopro_order_item')->where('id',$aftersale['order_item_id'])->find();
        $good_shopro_store_id = $order_item['good_shopro_store_id'];
        $stroe_user_id = Db::name('shopro_user_store')->where('store_id',$good_shopro_store_id)->find();

        $user = Db::name('user')->where('id',$order_item['user_id'])->find();
        $createtime = date('Y-m-d H:i:s', $aftersale['createtime']);
        $order = Db::name('shopro_order')->where('id',$order_item['order_id'])->find();

        file_put_contents("tuikuan_shangjia_notice.txt",'09'.json_encode(2).PHP_EOL, FILE_APPEND|LOCK_EX);
        $unionid = Db::name('shopro_user_oauth')->where('user_id',$stroe_user_id['user_id'])->value('unionid');
        $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');

        file_put_contents("tuikuan_shangjia_notice.txt",'09'.'|'.$stroe_user_id['user_id'].PHP_EOL, FILE_APPEND|LOCK_EX);
        if ($gzh_openid){
            file_put_contents("tuikuan_shangjia_notice.txt",'09'.json_encode(3).PHP_EOL, FILE_APPEND|LOCK_EX);
            file_put_contents("tuikuan_shangjia_notice.txt",'09'.json_encode([
                    'touser' => $gzh_openid,
                    'template_id' => 'r_fsaY_jIRHLrqKNYjNgYPf9lalqWF87cZiZfgmlieg',
                    'miniprogram'=>[
                        'appid'=>$app_id,
                        'pagepath'=>'pages/app/merchant/index?storeId='.$good_shopro_store_id,
                    ],
                    'data' => [
                        'first'    => array('value' => '有人申请售后啦！', 'color' => '#ff0000'),
                        'keyword1' => array('title' => '服务单号', 'value' => $order['order_sn'], 'color' => '#000000'),
                        'keyword2' => array('title' => '申请时间', 'value' => $createtime, 'color' => '#000000'),
                        'keyword3' => array('title' => '申请原因', 'value' => $content, 'color' => '#000000'),

//                    'remark' => array('title' => '备注', 'value' => '团购名称：'.$groupon_info['nickname'], 'color' => '#000000'),
                    ]
                ]).PHP_EOL, FILE_APPEND|LOCK_EX);
            \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                'touser' => $gzh_openid,
                'template_id' => 'r_fsaY_jIRHLrqKNYjNgYPf9lalqWF87cZiZfgmlieg',
                'miniprogram'=>[
                    'appid'=>$app_id,
                    'pagepath'=>'pages/app/merchant/index?storeId='.$good_shopro_store_id,
                ],
                'data' => [
                    'first'    => array('value' => '有人申请售后啦！', 'color' => '#ff0000'),
                    'keyword1' => array('title' => '服务单号', 'value' => $order['order_sn'], 'color' => '#000000'),
                    'keyword2' => array('title' => '申请时间', 'value' => $createtime, 'color' => '#000000'),
                    'keyword3' => array('title' => '申请原因', 'value' => $content, 'color' => '#000000'),

//                    'remark' => array('title' => '备注', 'value' => '团购名称：'.$groupon_info['nickname'], 'color' => '#000000'),
                ]
            ], 'shopro');
        }


    }
}
//已对接（微信订单确认收货后发送）
/**
 * 收货通知
 * @param array $param
 * @return bool|string
 */
if (!function_exists('receiving_notification')) {
    function receiving_notification($order_item_id){//订单规格ID
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];

        $order_item = Db::name('shopro_order_item')->where('id',$order_item_id)->find();

        $unionid = Db::name('shopro_user_oauth')->where('user_id',$order_item['user_id'])->value('unionid');
        $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');
        if ($gzh_openid){

            \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                'touser' => $gzh_openid,
                'template_id' => 'GHi8l7KHwW6jxg-Ov-aHQh62kjluTnA97WdGN1Wwk0k',
                'miniprogram'=>[
                    'appid'=>$app_id,
                    'pagepath'=>'pages/order/list',
                ],
                'data' => [
                    'first'    => array('value' => '您好，您有订单已收货', 'color' => '#ff0000'),
                    'keyword1' => array('title' => '商品', 'value' => $order_item['goods_title'], 'color' => '#000000'),
                    'keyword2' => array('title' => '订单号', 'value' => Db::name('shopro_order')->where('id',$order_item['order_id'])->value('order_sn'), 'color' => '#000000'),

                ]
            ], 'shopro');
        }


    }
}
/**
 * 小团长申请，加模板消息。
 * @param array $param
 * @return bool|string
 */
if (!function_exists('mini_apply')) {
    function mini_apply($user_id,$user_id_mini){//团长用户ID，申请人ID
        $wx_config = Db::name('shopro_config')->where(['name'=>'wxMiniProgram'])->value('value');
        $wx_config_array = json_decode($wx_config,true);
        $app_id = $wx_config_array['app_id'];

        $apply_mini_info = Db::name('user')->where('id',$user_id_mini)->find();


        $unionid = Db::name('shopro_user_oauth')->where('user_id',$user_id)->value('unionid');
        $gzh_openid = Db::name('shopro_wechat_fans')->where('unionid',$unionid)->value('openid');
        $username = Db::name('user')->where('id',$user_id)->value('username');
        if ($gzh_openid){

            \think\Queue::push('\addons\shopro\job\Queuejob@official_account_push_message', [
                'touser' => $gzh_openid,
                'template_id' => 'ZRem3v-UjqWoS4T-nt4C93JcsCbB2jpASw1By22MNVc',
                'miniprogram'=>[
                    'appid'=>$app_id,
                    'pagepath'=>'pages/activity/groupon/my-groupon',
                ],
                'data' => [
                    'first'    => array('value' => $username.'，有新的小团长申请', 'color' => '#ff0000'),
                    'keyword1' => array('title' => '服务名称', 'value' => '申请成为您的小团长  ', 'color' => '#000000'),
                    'keyword2' => array('title' => '生效时间', 'value' => date('Y-m-d H:i:s', time()), 'color' => '#000000'),
                    'keyword3' => array('title' => '服务内容', 'value' =>'申请人：'.$apply_mini_info['nickname'], 'color' => '#000000'),
                    'remark' => array('title' => '服务内容', 'value' =>'点击进入小程序团长中心进行操作', 'color' => '#000000'),
                ]
            ], 'shopro');
        }


    }
}

//已对接（抖音订单核销成功后发送）
/**
 * 抖音消费成功通知
 * @param array $param
 * @return bool|string
 */
if (!function_exists('douyin_sms_success')) {
    function douyin_sms_success($mobile,$data){//手机号  模板变量

//        $er=\app\common\library\Sms::notice($mobile, ['goods_name'=>'IphoneX','code'=>'ADSFSFSD','time'=>'2022/02/10'], $config['template']['success']);
//        您购买的 ${goods_name}，券码 ${code}，已于${time} 消费成功。如有疑问，请访问抖音小程序 咨询。祝您生活愉快！
        $config = get_addon_config('alisms');
        $er=\app\common\library\Sms::notice($mobile, $data, $config['template']['success']);
        return $er;
    }
}
//已对接（抖音订单售后平台同意退款后发送）
/**
 * 抖音发起退款通知
 * @param array $param
 * @return bool|string
 */
if (!function_exists('douyin_sms_refund')) {
    function douyin_sms_refund($mobile,$data){//手机号  模板变量
//        $er=\app\common\library\Sms::notice($mobile, ['goods_name'=>'IphoneX','money'=>'0.01','time'=>'2022/02/10'], $config['template']['success']);
//        您购买的 ${goods_name} 已发起退款，退款金额${money}元将在${time}个工作日内原路返回，请注意查收.祝您生活愉快！
        $config = get_addon_config('alisms');
        $er=\app\common\library\Sms::notice($mobile, $data, $config['template']['refund']);
        return $er;
    }
}
//已对接（抖音订单支付成功后发送）
/**
 * 抖音成功购买通知
 * @param array $param
 * @return bool|string
 */
if (!function_exists('douyin_sms_buy')) {
    function douyin_sms_buy($mobile,$data){//手机号  模板变量
//        $er=\app\common\library\Sms::notice($mobile, ['goods_name'=>'IphoneX','code'=>'asdfcvfdf'], $config['template']['success']);
//        您已成功购买 ${goods_name} 商品，券码 ${code}，访问抖音小程序 查看订单。祝您生活愉快！
        $config = get_addon_config('alisms');
        $er=\app\common\library\Sms::notice($mobile, $data, $config['template']['buy']);
        return $er;
    }
}
/**
 * 获取微信公众号 access_token
 * @return mixed
 */
if (!function_exists('get_public_access_token')) {
    function get_public_access_token(){
        $access_token = cache('wx_public_access_token');
        file_put_contents("access_token.json",'get_public_access_token:'.json_encode($access_token).PHP_EOL, FILE_APPEND|LOCK_EX);
        if (empty($access_token)){
            //单商户的配置 获取微信公众配置
            $wx_config = Db::name('shopro_config')->where(['name'=>'wxOfficialAccount'])->value('value');
            $wx_config_array = json_decode($wx_config,true);
            $app_id = $wx_config_array['app_id'];
            $secret = $wx_config_array['secret'];

            //多商户的配置
            /*$config = get_addon_config('wanlshop');
            $app_id = $config['sdk_qq']['gz_appid'];
            $secret = $config['sdk_qq']['gz_secret'];*/

            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' .$app_id . '&secret=' . $secret;

            $curl=curl_init();
            curl_setopt($curl,CURLOPT_URL,$url);
            curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
            curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
            curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
            $result = curl_exec($curl);
            // 打印返回的内容
            file_put_contents("access_token.json",'get_public_access_token:$result:'.json_encode($result).PHP_EOL, FILE_APPEND|LOCK_EX);
            curl_close($curl);
            $data = json_decode($result,true);
            $access_token = $data['access_token'];
            cache('wx_public_access_token',$access_token,7000);
        }

        return $access_token;
    }

}
/**
 * 获取微信公众号 access_token
 * @return mixed
 */
if (!function_exists('get_douyin_access_token')) {
    function get_douyin_access_token(){
        cache('douyin_public_access_token',null);
        $access_token = cache('douyin_public_access_token');

        if (empty($access_token)){
            //单商户的配置 获取微信公众配置
            $wx_config = Db::name('shopro_config')->where(['name'=>'ziJieMiniProgram'])->value('value');
            $wx_config_array = json_decode($wx_config,true);
            $app_id = $wx_config_array['appid'];
            $secret = $wx_config_array['secret'];
            $url = 'https://developer.toutiao.com/api/apps/token';
            $result = beng_curl($url.'?appid='.$app_id.'&secret='.$secret.'&grant_type=client_credential');
            $data = json_decode($result,true);
            $access_token = $data['access_token'];
            cache('douyin_public_access_token',$access_token,3600);
            return $access_token;
        }
        return $access_token;
    }

}
if (!function_exists('beng_curl')) {
    function beng_curl($url, $paras = [])
    {
//        echo beng_curl("https://api.oioweb.cn/api/beian.php?url=qq.com");
//        echo beng_curl("https://api.oioweb.cn/api/beian.php",[
//            'post'=>[
//                'url'=>'qq.com'
//            ]
//        ]);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if (isset($paras['Header'])) {
            $Header = $paras['Header'];
        } else {
            $Header[] = "Accept:*/*";
            $Header[] = "Accept-Encoding:gzip,deflate,sdch";
            $Header[] = "Accept-Language:zh-CN,zh;q=0.8";
            $Header[] = "Connection:close";
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $Header);
        if (isset($paras['ctime'])) { // 连接超时
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $paras['ctime']);
        } else {
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        }
        if (isset($paras['rtime'])) { // 读取超时
            curl_setopt($ch, CURLOPT_TIMEOUT, $paras['rtime']);
        }
        if (isset($paras['post'])) {

            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $paras['post']);
        }
        if (isset($paras['header'])) {
            curl_setopt($ch, CURLOPT_HEADER, true);
        }
        if (isset($paras['cookie'])) {
            curl_setopt($ch, CURLOPT_COOKIE, $paras['cookie']);
        }
        if (isset($paras['refer'])) {
            if ($paras['refer'] == 1) {
                curl_setopt($ch, CURLOPT_REFERER, 'http://m.qzone.com/infocenter?g_f=');
            } else {
                curl_setopt($ch, CURLOPT_REFERER, $paras['refer']);
            }
        }
        if (isset($paras['ua'])) {
            curl_setopt($ch, CURLOPT_USERAGENT, $paras['ua']);
        } else {
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
        }
        if (isset($paras['nobody'])) {
            curl_setopt($ch, CURLOPT_NOBODY, 1);
        }
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if (isset($paras['GetCookie'])) {
            curl_setopt($ch, CURLOPT_HEADER, 1);
            $result = curl_exec($ch);
            preg_match_all("/Set-Cookie: (.*?);/m", $result, $matches);
            $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $header = substr($result, 0, $headerSize); //状态码
            $body = substr($result, $headerSize);
            $ret = [
                "Cookie" => $matches, "body" => $body, "header" => $header, 'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
            ];
            curl_close($ch);
            return $ret;
        }

        $ret = curl_exec($ch);

        if (isset($paras['loadurl'])) {
            $Headers = curl_getinfo($ch);
            if (isset($Headers['redirect_url'])) {
                $ret = $Headers['redirect_url'];
            } else {
                $ret = false;
            }
        }
        curl_close($ch);
        return $ret;
    }
}
if (!function_exists('multi_array_sort')) {
    function multi_array_sort($multi_array, $sort_key, $sort = SORT_DESC) {
        foreach ($multi_array as $row_array) {
            $key_array[] = $row_array[$sort_key];
        }

        array_multisort($key_array, $sort, $multi_array);
        return $multi_array;
    }
}
if (!function_exists('distance')) {
    function distance($lat1, $lng1, $lat2, $lng2, $miles = true) {
        $pi80 = M_PI / 180;
        $lat1 *= $pi80;
        $lng1 *= $pi80;
        $lat2 *= $pi80;
        $lng2 *= $pi80;
        $r = 6372.797; // mean radius of Earth in km
        $dlat = $lat2 - $lat1;
        $dlng = $lng2 - $lng1;
        $a = sin($dlat/2)*sin($dlat/2)+cos($lat1)*cos($lat2)*sin($dlng/2)*sin($dlng/2);
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
        $km = $r * $c;
        return ($miles ? ($km * 0.621371192) : $km);
    }
}



/**
 * 下划线转驼峰
 * step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
 * step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
 */
if (!function_exists('camelize')) {
    function camelize($uncamelized_words, $separator = '_') {
        $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
        return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
    }
}
    
/**
 * 驼峰命名转下划线命名
 * 思路:
 * 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
 */
if (!function_exists('uncamelize')) {
    function uncamelize($camelCaps, $separator='_')
    {
        return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
    }
}


/**
 * 检测系统必要环境
 */
if (!function_exists('checkEnv')) {
    function checkEnv($need = [], $is_throw = true)
    {
        $need = is_string($need) ? [$need] : $need;

        // 检测是否安装浮点数运算扩展
        if (in_array('bcmath', $need)) {
            if (!extension_loaded('bcmath')) {
                if ($is_throw) {
                    new \addons\shopro\exception\Exception('请安装浮点数扩展 【bcmath】');
                } else {
                    return false;
                }
            }
        }

        // 检测是否安装了队列
        if (in_array('queue', $need)) {
            if (!class_exists(\think\Queue::class)) {
                if ($is_throw) {
                    new \addons\shopro\exception\Exception('请安装 【topthink/think-queue:v1.1.6 队列扩展】');
                } else {
                    return false;
                }
            }
        }

        if (in_array('commission', $need)) {
            if (!class_exists(\addons\shopro\listener\commission\CommissionHook::class)) {
                if ($is_throw) {
                    new \addons\shopro\exception\Exception('请先升级 【shopro】');
                } else {
                    return false;
                }
            }
        }

        if (in_array('yansongda', $need)) {
            if (!class_exists(\Yansongda\Pay\Pay::class)) {
                if ($is_throw) {
                    new \addons\shopro\exception\Exception('请在后台安装 【微信支付宝整合插件】');
                } else {
                    return false;
                }
            }
        }
        return true;
    }
}


/**
 * 删除 sql mode 指定模式，或者直接关闭 sql mode
 */
if (!function_exists('closeStrict')) {
    function closeStrict($modes = [])
    {
        $modes = array_filter(is_array($modes) ? $modes : [$modes]);

        $result = \think\Db::query("SELECT @@session.sql_mode");
        $newModes = $oldModes = explode(',', ($result[0]['@@session.sql_mode'] ?? ''));

        if ($modes) {
            foreach ($modes as $mode) {
                $delkey = array_search($mode, $newModes);
                if ($delkey !== false) {
                    unset($newModes[$delkey]);
                }
            }
            $newModes = join(',', array_values(array_filter($newModes)));
        } else {
            $newModes = '';
        }

        \think\Db::execute("set session sql_mode='" . $newModes . "'");

        return $oldModes;
    }
}


/**
 * 重新打开被关闭的 sql mode
 */
if (!function_exists('recoverStrict')) {
    function recoverStrict($modes = [], $append = false)
    {
        if ($append) {
            $result = \think\Db::query("SELECT @@session.sql_mode");
            $oldModes = explode(',', ($result[0]['@@session.sql_mode'] ?? ''));

            $modes = array_values(array_filter(array_unique(array_merge($oldModes, $modes))));
        }

        \think\Db::execute("set session sql_mode='" . join(',', $modes) . "'");
    }
}